package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.websocket.servlet.TomcatWebSocketServletWebServerCustomizer;
import org.springframework.boot.web.servlet.filter.OrderedFormContentFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户订单服务层实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //校验数据，检查用户地址是否为空
        AddressBook addressBook = addressBookMapper.getAddressBookById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        //设置用户ID
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //查询购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectShoppingCart(shoppingCart);
        //检测是否为空
        if(shoppingCartList == null || shoppingCartList.isEmpty()){
            //购物车数据为空则 购物车数据为空，不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //插入一条订单信息
        Orders orders = new Orders();
        //属性拷贝
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //插入需要的参数
        //插入订单时间
        orders.setOrderTime(LocalDateTime.now());
        //插入订单支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //插入订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //通过java自带的当前时间设置当前的订单号
        //设置订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //设置订单手机号
        orders.setPhone(addressBook.getPhone());
        //设置订单收货人
        orders.setConsignee(addressBook.getConsignee());
        //设置订单用户ID
        orders.setUserId(BaseContext.getCurrentId());
        //设置订单用户地址
        orders.setAddress(addressBook.getDetail());
        //插入订单表数据
        orderMapper.insert(orders);

        //插入多条订单详情信息
        //建议批量插入
        List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
        for (ShoppingCart cart : shoppingCartList) {
            //实例化订单详情
            OrderDetail orderDetail = new OrderDetail();
            //设置订单详情ID
            orderDetail.setOrderId(orders.getId());
            //属性拷贝
            BeanUtils.copyProperties(cart,orderDetail);
            //在订单详情的集合中添加组合的订单详情
            orderDetailList.add(orderDetail);
            //将订单详情插入表格
            orderDetailMapper.insertBatch(orderDetailList);
        }

        //清空购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        //返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        //设置订单ID
        orderSubmitVO.setId(orders.getId());
        //设置订单号码
        orderSubmitVO.setOrderNumber(orders.getNumber());
        //设置订单时间
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        //设置订单金额
        orderSubmitVO.setOrderAmount(orders.getAmount());
        //返回组装数据
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code","ORDERPAID");
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);

        //更新订单状态
        Orders orders = new Orders();
        //待接单
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        //已支付
        orders.setPayStatus(Orders.PAID);
        //修改时间
        orders.setOrderTime(LocalDateTime.now());

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        //设置订单ID
        orders.setId(ordersDB.getId());

        //更新数据库
        orderMapper.update(orders);
        //实例化微信支付的端口 VO 实体类
        OrderPaymentVO vo = new OrderPaymentVO();
        //设置已付款
        vo.setPackageStr(String.valueOf(Orders.PAID));
        //返回数据
        return vo;
    }

    /**
     * 通过订单ID获取当前订单信息以及订单详情信息
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderAndDetailByOrderId(Long id) {
        //通过订单ID获取当前的订单信息
        Orders orders = orderMapper.selectOrderByOrderId(id);
        //通过订单ID获取当前订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(id);
        //组合 订单VO
        OrderVO orderVO = new OrderVO();
        //属性拷贝
        BeanUtils.copyProperties(orders,orderVO);
        //设置订单详情
        orderVO.setOrderDetailList(orderDetailList);
        //返回 订单VO
        return orderVO;
    }

    /**
     * 通过订单ID取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectOrderByOrderId(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //实例化订单 进行组装
        Orders orders = new Orders();
        //设置订单ID
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
//
//            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        //更新订单状态
        orders.setStatus(Orders.CANCELLED);
        //订单取消原因
        orders.setCancelReason("用户取消");
        //订单取消时间
        orders.setCancelTime(LocalDateTime.now());
        //更新订单
        orderMapper.update(orders);

    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult historyOrders(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);
        //设置分页内容
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailByOrderId(orderId);
                //组装分页数据
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                //将数据添加至集合中
                list.add(orderVO);
            }
        }
        //返回分页数据
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    @Transactional
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    /**
     * 管理端订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置参数 用户ID
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //新插件 Spring 中的工具
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //通过前端传递的参数进行分页查询（查询出每页的订单信息集合）
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        //查询完毕之后通过每页的订单，查询相关的订单详情信息进行封装到 orderVO
        List<OrderVO> list = new ArrayList();
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                //组合分页数据
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailMapper.selectOrderDetailByOrderId(orders.getId()));
                list.add(orderVO);
            }
        }
        //返回分页数据
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectOrderByOrderId(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        //设置订单ID
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //更新订单
        orderMapper.update(orders);

    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //设置订单相关属性
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        //更新订单
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectOrderByOrderId(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            //设置退款
            orders.setPayStatus(Orders.REFUND);
        }
        //设置订单ID
        orders.setId(ordersDB.getId());
        //设置订单状态
        orders.setStatus(Orders.CANCELLED);
        //设置拒单原因
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        //设置拒单时间
        orders.setCancelTime(LocalDateTime.now());
        //更新数据
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectOrderByOrderId(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        //设置订单ID
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        //设置完成订单的时间
        orders.setDeliveryTime(LocalDateTime.now());
        //更新订单数据
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectOrderByOrderId(ordersCancelDTO.getId());
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);

            //取消之后退款（如果支付状态为 1 则需要退款）
            orders.setPayStatus(Orders.REFUND);
        }
        //订单ID
        orders.setId(ordersCancelDTO.getId());
        //订单状态
        orders.setStatus(Orders.CANCELLED);
        //取消原因
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        //取消时间
        orders.setCancelTime(LocalDateTime.now());
        //更细数据
        orderMapper.update(orders);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {

        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        //待接单
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        //待派送
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        //派送中
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //设置待接单
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        //设置待派送
        orderStatisticsVO.setConfirmed(confirmed);
        //设置派送中
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        //返回数据
        return orderStatisticsVO;

    }

}
